import { App } from "vue";
import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import {createRouterGuards}from './router-guards'
const modules: Record<
  string,
  Record<string, RouteRecordRaw[]>
> = import.meta.globEager("./modules/*.ts");

const routeModuleList: RouteRecordRaw[] = [];

// 拼接需要权限
Object.keys(modules).forEach((key: string) => {
  const mod = modules[key].default || {};
  const modList = Array.isArray(mod) ? [...mod] : [mod];
  routeModuleList.push(...modList);
});

const sortRoute = (a:any, b:any) => {
  return (a?.meta.sort || 0) - (b?.meta.sort || 0)
}

routeModuleList.sort(sortRoute)

/**
 * 根路由
 */
const RootRoute:RouteRecordRaw = {
    path:'/',
    name:'root',
    component:() => import('@/view/login/index.vue'),
    meta:{
        title:'登录'
    }
}
/**
 * 登录路由
 */
const LoginRoute:RouteRecordRaw = {
    path:'/login',
    name:'login',
    component:() => import('@/view/login/index.vue'),
    meta:{
        title:'登录'
    }
}

//需要验证权限
export const asyncRoutes = [...routeModuleList];


/**
 * 无权限路由组
 */
export const constantRouter:RouteRecordRaw[] = [RootRoute,LoginRoute]


const router = createRouter({
    routes:constantRouter,
    history: createWebHistory(),
})

export function setupRouter(app:App){
    app.use(router)
    createRouterGuards(router)
}

export default router